/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.admin.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.MessageNamespaces;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.object.Directory;
import etcore.webapp.grouptalk.common.object.Group;
import etcore.webapp.grouptalk.common.object.GroupDirectoryRelationship;
import etcore.webapp.grouptalk.common.service.CommentService;
import etcore.webapp.grouptalk.common.service.DirectoryService;
import etcore.webapp.grouptalk.common.service.GroupDirectoryRelationshipService;
import etcore.webapp.grouptalk.common.service.GroupService;
import etcore.webapp.grouptalk.common.service.MessageService;

/**
 * This action validates the request and executes the command of showing the
 * group administration page,then set the corresponding attributes for output
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class GroupAdminAction extends AbstractAction {

	private static final long serialVersionUID = -164285303564406088L;
	// validate result
	public static final int ACCESS_ALLOWED = 0;
	public static final int ERROR = 1;
	public static final int NOT_LOGGED = 2;
	public static final String ONE = "1";
	public static final String ZERO = "0";
	public static final String TEN_THOUSAND = "10000";
	// parameter/attributes constants

	public static final String KEY = "key";

	public static final String GROUP_MSG_COUNT = "groupMsgCount";
	public static final String TODAY_GROUP_MSG_COUNT = "todayGroupMsgCount";

	public static final String ADD_DIRECTORY = "addDirectory";
	public static final String EDIT_DIRECTORY = "editDirectory";
	public static final String DEL_DIRECTORY = "delDirectory";
	public static final String PROCESS_BLOCK = "processBlock";

	// utility constants

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {

		boolean isAdmin = (Boolean) request.getAttribute(PageConstants.ISADMIN);
		boolean notLogged = (Boolean) request
				.getAttribute(PageConstants.NOTLOGGED);
		if (notLogged)
			return NOT_LOGGED;
		if (isAdmin) {

			return ACCESS_ALLOWED;
		}

		return ERROR;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (NOT_LOGGED == validationResult) {
			request.setAttribute("init", "login");
			return "/";
		}
		if (ERROR == validationResult)
			return PageConstants.ACTION_PATH_ERROR;
		return PageConstants.PAGE_PATH_GROUPADMIN;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		addDirectory(request);
		editDirectory(request);
		delDirectory(request);
		processBlock(request);
		getDirectories(request);
	}

	private void getDirectories(HttpServletRequest request) {
		String open = request.getParameter(PageConstants.OPEN);
		String nav = request.getParameter(PageConstants.NAV);
		if (open != null) {
			List<Group> rootGroups = null;
			DirectoryService directoryService = new DirectoryService();
			GroupService groupService = new GroupService();
			MessageService messageService = new MessageService();
			CommentService commentService = new CommentService();
			int parent = 0;
			if (PageConstants.INFO_OPEN_VALUE.equals(open)
					&& PageConstants.NAV_DISABLED_VALUE.equals(nav)) {

				parent = -1;
				rootGroups = groupService.findGroupsByNotInDirectories(
						new Integer(open), new Integer(nav), parent);
			} else if (PageConstants.COMMUNITIES_OPEN_VALUE.equals(open)
					&& PageConstants.NAV_DISABLED_VALUE.equals(nav)) {
				parent = -2;
				rootGroups = groupService.findGroupsByNotInDirectories(
						new Integer(open), new Integer(nav), parent);

			} else if (PageConstants.INTERNAL_OPEN_VALUE.equals(open)) {
				parent = 0;
				rootGroups = groupService.findGroupsByNotInDirectories(
						new Integer(open), parent);
			} else if (PageConstants.BOOKMARKS_OPEN_VALUE.equals(open)) {
				parent = -3;
				rootGroups = groupService.findGroupsByNotInDirectories(
						new Integer(open), parent);
			} else if (PageConstants.REMINDERS_OPEN_VALUE.equals(open)) {
				parent = -4;
				rootGroups = groupService.findGroupsByNotInDirectories(
						new Integer(open), parent);
			} else if (PageConstants.INFO_OPEN_VALUE.equals(open)
					&& PageConstants.NAV_ENABLED_VALUE.equals(nav)) {
				parent = -11;
				rootGroups = groupService.findGroupsByNotInDirectories(
						new Integer(open), new Integer(nav), parent);
			} else if (PageConstants.COMMUNITIES_OPEN_VALUE.equals(open)
					&& PageConstants.NAV_ENABLED_VALUE.equals(nav)) {
				parent = -22;
				rootGroups = groupService.findGroupsByNotInDirectories(
						new Integer(open), new Integer(nav), parent);
			}

			request.setAttribute("rootGroups", rootGroups);
			if (rootGroups != null) {
				for (Group group : rootGroups) {
					long groupMsgCount = messageService.findSizeByGid(group
							.getId())
							+ commentService.searchSizeByGid(group.getId());
					long todayGroupMsgCount = messageService
							.findSizeByDaysAndGid(1, group.getId())
							+ commentService.searchSizeByGidAndDays(
									group.getId(), 1);
					request.setAttribute(group.getId() + GROUP_MSG_COUNT,
							groupMsgCount);
					request.setAttribute(group.getId() + TODAY_GROUP_MSG_COUNT,
							todayGroupMsgCount);
				}
			}

			List<Directory> directories = directoryService.findByParent(parent);

			for (Directory directory : directories) {
				List<Group> groups = groupService.findGroupsByDid(directory
						.getId());
				request.setAttribute(directory.getId() + PageConstants.GROUPS,
						groups);
				for (Group group : groups) {
					long groupMsgCount = messageService.findSizeByGid(group
							.getId())
							+ commentService.searchSizeByGid(group.getId());
					long todayGroupMsgCount = messageService
							.findSizeByDaysAndGid(1, group.getId())
							+ commentService.searchSizeByGidAndDays(
									group.getId(), 1);
					request.setAttribute(group.getId() + GROUP_MSG_COUNT,
							groupMsgCount);
					request.setAttribute(group.getId() + TODAY_GROUP_MSG_COUNT,
							todayGroupMsgCount);
				}

			}

			request.setAttribute("directories", directories);
			if (directories != null)
				request.setAttribute("directoriesCount", directories.size());

		}
	}

	private void addDirectory(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		String open = request.getParameter(PageConstants.OPEN);
		String nav = request.getParameter(PageConstants.NAV);
		String name = request.getParameter(PageConstants.NAME);
		String up = request.getParameter(PageConstants.UP);
		String local = request.getParameter(Messages.LANG_LOCAL);
		String en = request.getParameter(Messages.LANG_EN);
		if (ADD_DIRECTORY.equals(cmd) && open != null && name != null) {
			DirectoryService directoryService = new DirectoryService();
			int parent = 0;
			if (PageConstants.INFO_OPEN_VALUE.equals(open)
					&& PageConstants.NAV_DISABLED_VALUE.equals(nav))
				parent = -1;
			if (PageConstants.COMMUNITIES_OPEN_VALUE.equals(open)
					&& PageConstants.NAV_DISABLED_VALUE.equals(nav))
				parent = -2;
			if (PageConstants.INTERNAL_OPEN_VALUE.equals(open))
				parent = 0;
			if (PageConstants.BOOKMARKS_OPEN_VALUE.equals(open))
				parent = -3;
			if (PageConstants.REMINDERS_OPEN_VALUE.equals(open))
				parent = -4;
			if (PageConstants.INFO_OPEN_VALUE.equals(open)
					&& PageConstants.NAV_ENABLED_VALUE.equals(nav))
				parent = -11;
			if (PageConstants.COMMUNITIES_OPEN_VALUE.equals(open)
					&& PageConstants.NAV_ENABLED_VALUE.equals(nav))
				parent = -22;
			Directory directory = new Directory();
			directory.setName(name);
			directory.setParent(parent);
			if (up != null)
				directory.setUp(new Integer(up));
			if (en != null)
				directory.setEn(new Integer(en));
			if (local != null)
				directory.setLocal(new Integer(local));
			directoryService.save(directory);
			HttpSession session = request.getSession(true);
			String msg = null;
			String lang = (String) session.getAttribute(Messages.LANG);
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_SUCCESS);
			} else {
				msg = Messages.getLabel(Messages.MSG_SUCCESS);
			}
			request.setAttribute(PageConstants.MSG, msg);
		}

	}

	private void editDirectory(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);

		// String nav = request.getParameter(PageConstants.NAV);
		String did = request.getParameter("did");
		String name = request.getParameter(PageConstants.NAME);
		String up = request.getParameter(PageConstants.UP);
		String local = request.getParameter(Messages.LANG_LOCAL);
		String en = request.getParameter(Messages.LANG_EN);
		if (EDIT_DIRECTORY.equals(cmd) && name != null && did != null) {
			DirectoryService directoryService = new DirectoryService();
			Directory directory = directoryService.findById(new Integer(did));
			if (directory != null) {
				if (!directory.getName().equals(name))
					directory.setName(name);
				if (up != null)
					directory.setUp(new Integer(up));
				if (en != null)
					directory.setEn(new Integer(en));
				if (local != null)
					directory.setLocal(new Integer(local));

				directoryService.merge(directory);
				HttpSession session = request.getSession(true);
				String msg = null;
				String lang = (String) session.getAttribute(Messages.LANG);
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_SUCCESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_SUCCESS);
				}
				request.setAttribute(PageConstants.MSG, msg);
			}
		}

	}

	private void delDirectory(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		String open = request.getParameter(PageConstants.OPEN);
		// String nav = request.getParameter(PageConstants.NAV);
		String did = request.getParameter("did");

		if (DEL_DIRECTORY.equals(cmd) && open != null && did != null) {
			DirectoryService directoryService = new DirectoryService();
			Directory directory = directoryService.findById(new Integer(did));
			if (directory != null) {

				directoryService.deleteSingle(directory);
				HttpSession session = request.getSession(true);
				String msg = null;
				String lang = (String) session.getAttribute(Messages.LANG);
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_SUCCESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_SUCCESS);
				}
				request.setAttribute(PageConstants.MSG, msg);
			}
		}

	}

	private void processBlock(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		String open = request.getParameter(PageConstants.OPEN);

		String did = request.getParameter("did");
		String gid = request.getParameter(PageConstants.GID);
		if (PROCESS_BLOCK.equals(cmd) && open != null && did != null
				&& gid != null) {
			GroupDirectoryRelationshipService relationService = new GroupDirectoryRelationshipService();
			if ("0".equals(did)) {
				List<GroupDirectoryRelationship> relationships = relationService
						.findByProperty("gid", new Integer(gid));
				relationService.deleteList(relationships);

			} else {
				List<GroupDirectoryRelationship> relationships = relationService
						.findByGidAndDid(new Integer(gid), new Integer(did));
				if (relationships != null && relationships.size() > 0)
					return;
				List<GroupDirectoryRelationship> oldRelationships = relationService
						.findByProperty("gid", new Integer(gid));
				relationService.deleteList(oldRelationships);
				GroupDirectoryRelationship relationship = new GroupDirectoryRelationship();
				relationship.setDid(new Integer(did));
				relationship.setGid(new Integer(gid));
				relationService.save(relationship);

			}

			HttpSession session = request.getSession(true);
			String msg = null;
			String lang = (String) session.getAttribute(Messages.LANG);
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_SUCCESS);
			} else {
				msg = Messages.getLabel(Messages.MSG_SUCCESS);
			}
			request.setAttribute(PageConstants.MSG, msg);
		}

	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/* (non-Javadoc)
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		List<String> namespaces = new ArrayList<String>();
		namespaces.add(MessageNamespaces.GROUP_ADMIN);
		return namespaces;
	}

}
